﻿using DMC300Axis_IO.Function;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using csLTDMC;
using OCR;
using System.Windows.Forms;
using OCR.Config;
using OCR.SystemThread;
using System.Drawing;
using System.IO;

namespace OCR.SystemThread
{
    public class CameraTriggerThread
    {
        public static bool CameraTrigger_Flowrec = false;
        public static bool CameraTrigger_OnLive = false;
        public static Thread CameraTriggerFlow_Thread = null;
        public static int iCameraTrigger_Step = 0;

        public static bool CameraTrigger_Stop = false;

        public static DateTime triggerDataTime;
        public static DateTime imgDateTime;

        public static Bitmap finalBit;
        public static DateTime dt1;
        public static DateTime dt2;
        public static DateTime dt2_Clone;
        public static DateTime dt_CompareResult;
        public static DateTime SendDt;
        public static DateTime SendNgDt;
        public static DateTime SendOKDt;

        public static DateTime stopCamDoDelay;
        public static string overTime;

        public static string noImgNG;

        public static bool isFinishSave;
        public static string currPath;
        //---自动运行之绪起动------------------------------------------------------------
        public static void CameraTrigger_Thread()
        {
            CameraTrigger_Flowrec = true;
            CameraTriggerFlow_Thread = new Thread(CameraTriggerFlowThread);
            CameraTriggerFlow_Thread.IsBackground = true;
            CameraTriggerFlow_Thread.Start();
            Console.WriteLine("iCameraTrigger_Step: "+ iCameraTrigger_Step); 
        }
        //-------------------------------------------------------------------------------
        //---自动运行流程----------------------------------------------------------------
        private static void CameraTriggerFlowThread(object obj)
        {
            while (CameraTrigger_Flowrec)
            {
                switch (iCameraTrigger_Step)
                {
                    case 0:
                        //AlgorithmModule.ImageHandleV2_Refresh(Application.StartupPath + "\\TemplateInput\\Refresh.bmp");
                        //AlgorithmModule_GPU.ImageHandleV2_Refresh_ByteArray("TemplateInput\\TestRefresh.bmp");
                        break;
                    case 1:
                        break;
                    case 10://  启动触发相机流程，并等待产品触碰到感测器
                        {
                            //AlgorithmModule_GPU.ImageHandleV2_Refresh_ByteArray("TemplateInput\\TestRefresh.bmp");
                            //if (DIO_Thread.Di[1] == 1 && !CameraTriggerTime_Config.CamearTriggerPause)
                            //{
                            //    triggerDataTime= DateTime.Now;
                            //    iCameraTrigger_Step = 15;
                            //}
                            if (CameraTriggerTime_Config.CamearTriggerPause)
                            {
                                iCameraTrigger_Step = 1;
                            }
                            if (IOThread_Run.Di[0] == 1)
                            {
                                LocalInfo.currState = "1";
                            }
                            else if (IOThread_Run.Di[0] == 0)
                            {
                                LocalInfo.currState = "0";
                                LocalInfo.lastState = LocalInfo.currState;
                            }

                            if (LocalInfo.lastState == "0" && LocalInfo.currState == "1")
                            {
                                Console.WriteLine("LocalInfo.currState:-----" + LocalInfo.currState);
                                Console.WriteLine("LocalInfo.lastState:-----"+ LocalInfo.lastState);

                                triggerDataTime = DateTime.Now;
                                LocalInfo.currCount += 1;

                                LocalInfo.lastDI_DT = triggerDataTime;

                                noImgNG = string.Empty;

                                IOThread_Run.DO_Trigger_olng(0, 1);

                                LocalInfo.lastState = LocalInfo.currState;

                                Thread.Sleep(50);

                                IOThread_Run.DO_Trigger_olng(0, 0);

                                iCameraTrigger_Step = 22;

                                //if (IOThread_Run.Di[0] == 1)
                                //{
                                //    triggerDataTime = DateTime.Now;
                                //    Console.WriteLine("DI_Interval:-----" + (triggerDataTime - LocalInfo.lastDI_DT).TotalMilliseconds);
                                //    //if ((triggerDataTime - LocalInfo.lastDI_DT).TotalMilliseconds < double.Parse(LocalInfo.RepeatSignalCheckTime))
                                //    //{
                                //    //    Console.WriteLine("多次触发");
                                //    //    LocalInfo.lastDI_DT = triggerDataTime;
                                //    //    break;

                                //    //}

                                //    LocalInfo.currCount += 1;

                                //    //CameraReceiveThread.isImageData = false;
                                //    //CameraReceiveThread.frameForSave = null;

                                //    if ((triggerDataTime - LocalInfo.lastDI_DT).TotalMilliseconds >= double.Parse(LocalInfo.DI_Interval))
                                //    {
                                //        //DateTime dt_CreateTxt = DateTime.Now;
                                //        //if (!File.Exists("DI_Time_Result.txt"))
                                //        //{
                                //        //    File.WriteAllText("DI_Time_Result.txt", null, Encoding.UTF8);
                                //        //}
                                //        //DateTime dt_WriteTxt = DateTime.Now;
                                //        //try
                                //        //{
                                //        //    Console.WriteLine("触发DI时间差：" + (triggerDataTime - LocalInfo.lastDI_DT).TotalMilliseconds);
                                //        //    StreamWriter sw = File.AppendText("DI_Time_Result.txt");
                                //        //    string DI_Time_Result = "上次触发DI时间：" + LocalInfo.lastDI_DT.ToString("yyyy:MM:dd:HH:mm:ss.fffffff")
                                //        //        + "  当前触发DI时间：" + triggerDataTime.ToString("yyyy:MM:dd:HH:mm:ss.fffffff")
                                //        //        + "  触发DI时间差：" + (triggerDataTime - LocalInfo.lastDI_DT).TotalMilliseconds;
                                //        //    Console.WriteLine(DI_Time_Result);
                                //        //    sw.WriteLine(DI_Time_Result);
                                //        //    sw.Close();
                                //        //}
                                //        //catch (Exception eX)
                                //        //{

                                //        //    Console.WriteLine(eX.Message);
                                //        //}
                                //        //DateTime dt_WriteEndTxt = DateTime.Now;
                                //    }

                                //    LocalInfo.lastDI_DT = triggerDataTime;

                                //    noImgNG = string.Empty;

                                //    IOThread_Run.DO_Trigger_olng(0, 1);

                                //    LocalInfo.lastState = LocalInfo.currState;

                                //    Thread.Sleep(50);

                                //    IOThread_Run.DO_Trigger_olng(0, 0);

                                //    iCameraTrigger_Step = 22;

                                //}
                            }




                            break;
                        }
                    case 15:   
                        {
    
                            break;
                        }
                    case 20:   //输出讯号触发相机取像
                        {
                            if ((DateTime.Now - triggerDataTime).TotalMilliseconds >= 260)
                            {
                                noImgNG = "触发相机超时260_无图NG";
                                iCameraTrigger_Step = 25;
                            }
                            else
                            {
                                IOThread_Run.DO_Trigger_olng(0, 1);

                                LocalInfo.lastState = LocalInfo.currState;

                                stopCamDoDelay = DateTime.Now;

                                iCameraTrigger_Step = 21;
                            }


                            break;
                        }
                    case 21:
                        {
                            if (CameraReceiveThread.isImageData)
                            {

                                IOThread_Run.DO_Trigger_olng(0, 0);
                                iCameraTrigger_Step = 22;
                            }
                            else
                            {
                                if ((DateTime.Now - stopCamDoDelay).TotalMilliseconds >= 100)
                                {
                                    Console.WriteLine("超过100是否拿到图： " + CameraReceiveThread.isImageData + "___" + (DateTime.Now - stopCamDoDelay).TotalMilliseconds);
                                    IOThread_Run.DO_Trigger_olng(0, 0);
                                    overTime = "  超时时间：" + DateTime.Now.ToString("yyyy:MM:dd:HH:mm:ss.ffff")
                                        + "  超时时长：" + (DateTime.Now - stopCamDoDelay).TotalMilliseconds;
                                    noImgNG = "取图超时100_无图NG";
                                    iCameraTrigger_Step = 25;
                                }
                            }

                            //if ((DateTime.Now - stopCamDoDelay).TotalMilliseconds >= 50)
                            //{
                            //    //Console.WriteLine("超过50是否拿到图："+ CameraReceiveThread.isImageData);

                            //    if ((DateTime.Now - stopCamDoDelay).TotalMilliseconds >= 100)
                            //    {
                            //        Console.WriteLine("超过100是否拿到图： " + CameraReceiveThread.isImageData+"___"+ (DateTime.Now - stopCamDoDelay).TotalMilliseconds);
                            //        IOThread_Run.DO_Trigger_olng(0, 0);
                            //        overTime = "  超时时间：" + DateTime.Now.ToString("yyyy:MM:dd:HH:mm:ss.ffff")
                            //            + "  超时时长：" + (DateTime.Now - stopCamDoDelay).TotalMilliseconds;
                            //        noImgNG = "取图超时100_无图NG";
                            //        iCameraTrigger_Step = 25;
                            //    }
                            //    else
                            //    {
                            //        Console.WriteLine("超过50是否拿到图： " + CameraReceiveThread.isImageData + "___" + (DateTime.Now - stopCamDoDelay).TotalMilliseconds);

                            //        IOThread_Run.DO_Trigger_olng(0, 0);

                            //        overTime = string.Empty;
                            //        iCameraTrigger_Step = 22;
                            //    }                                
                            //}
                            //else if ((DateTime.Now - stopCamDoDelay).TotalMilliseconds < 50)
                            //{
                            //    Console.WriteLine("小于50是否拿到图： " + CameraReceiveThread.isImageData + "___" + (DateTime.Now - stopCamDoDelay).TotalMilliseconds);

                            //    IOThread_Run.DO_Trigger_olng(0, 0);
                            //    iCameraTrigger_Step = 22;
                            //}
                            break;
                        }
                    case 22:
                        if (CameraTriggerTime_Config.CamearTriggerPause)
                        {
                            iCameraTrigger_Step = 1;
                        }
                        //AlgorithmModule_GPU.ImageHandleV2_Refresh_ByteArray("TemplateInput\\TestRefresh.bmp");
                        if (CameraReceiveThread.isImageData)
                        {
                            imgDateTime = DateTime.Now;
                            Console.WriteLine("isImageData-拿到图：" + imgDateTime.ToString("yyyy:MM:dd:HH:mm:ss:ffff"));

                            Console.WriteLine("triggerDataTime：{0} -imageDateTime：{1} -timeSpan：{2} ", triggerDataTime.TimeOfDay, imgDateTime.TimeOfDay, (imgDateTime - triggerDataTime).TotalMilliseconds);

                            dt1 = DateTime.Now;

                            //裁剪拼接
                            List<Rectangle> roiLocations = new List<Rectangle>();
                            Bitmap  cropBit = OCR_Form.StitchROIs_Middle(CameraReceiveThread.frameForSave.Image.ToBitmap(), LocalTemplateSingleInfos_Config.rectangles, out roiLocations);
                            //AlgorithmModule_GPU.ImageHandleV2_ByteArray(cropBit);
                            AlgorithmModule_GPU.ImageHandleV2_Opencv(cropBit);
                            //映射回原图
                            List<Rectangle> convertRectangles = OCR_Form.MapBackToOriginal(OCR_Form.ConvertToRectangles(AlgorithmModule_GPU.pointsList), roiLocations, LocalTemplateSingleInfos_Config.rectangles);
                            AlgorithmModule_GPU.pointsList = OCR_Form.ConvertToPointLists(convertRectangles);


                            //AlgorithmModule_GPU.ImageHandleV2_ByteArray(CameraReceiveThread.frameForSave.Image.ToBitmap());

                            //AlgorithmModule_GPU.ImageHandleV2_ByteArray(CameraReceiveThread.frameForSave.Image.PixelData, CameraReceiveThread.frameForSave.Image.Width, CameraReceiveThread.frameForSave.Image.Height,false);

                            //LocalInfo.totalCount += 1;
                            LocalInfo.totalCount += LocalInfo.Tem_RectMaxCount;
                            dt2 = DateTime.Now;

                            //finalBit = (Bitmap)CameraReceiveThread.frameForSave.Image.ToBitmap().Clone();
                            Image image = CameraReceiveThread.frameForSave.Image.ToBitmap();
                            finalBit = new Bitmap(image);


                            //CameraReceiveThread.isImageData = false;
                            //CameraReceiveThread.frameForSave = null;
                            dt2_Clone = DateTime.Now;

                            //bool isSame = LocalTemplateInfo.CompareTemplate(AlgorithmModule_GPU.mainInfos);

                            //bool isSame = LocalTemplateInfo.CompareTemplate_Disorder(AlgorithmModule_GPU.mainInfos);
                            LocalTemplateSingleInfos_Config.finalPointsList.Clear();
                            LocalTemplateSingleInfos_Config.mainInfos.Clear();
                            LocalTemplateSingleInfos_Config.temInfos.Clear();
                            for (int i = 0; i < LocalTemplateSingleInfos_Config.localTemplateSingleInfos.Count; i++)
                            {
                                for (int j = 0; j < LocalTemplateSingleInfos_Config.localTemplateSingleInfos[i].InfoList.Count; j++)
                                {
                                    LocalTemplateSingleInfos_Config.temInfos.Add(LocalTemplateSingleInfos_Config.localTemplateSingleInfos[i].InfoList[j]);
                                    Console.WriteLine("temInfos.Count:" + LocalTemplateSingleInfos_Config.temInfos.Count);
                                }

                            }

                            List<bool> isSameList = new List<bool>();
                            for (int i = 0; i < LocalTemplateSingleInfos_Config.localTemplateSingleInfos.Count; i++)
                            {
                                //LocalTemplateSingleInfos_Config.Compare(LocalTemplateSingleInfos_Config.rectangles[i], LocalTemplateSingleInfos_Config.infosList[i], LocalTemplateSingleInfos_Config.insideList[i], LocalTemplateSingleInfos_Config.finalPointsLists[i]);
                                LocalTemplateSingleInfos_Config.CompareConfuse(LocalTemplateSingleInfos_Config.rectangles[i], LocalTemplateSingleInfos_Config.infosList[i], LocalTemplateSingleInfos_Config.insideList[i], LocalTemplateSingleInfos_Config.finalPointsLists[i], LocalTemplateSingleInfos_Config.confuseMultiIndex[i], LocalTemplateSingleInfos_Config.confuseMultiIndexDic[i]);
                            }

                            for (int i = 0; i < LocalTemplateSingleInfos_Config.localTemplateSingleInfos.Count; i++)
                            {
                                isSameList.Add(LocalTemplateSingleInfos_Config.CompareTemplate_Disorder(LocalTemplateSingleInfos_Config.localTemplateSingleInfos[i].InfoList, LocalTemplateSingleInfos_Config.infosList[i]));
                            }
                            Console.WriteLine("isSameList:" + isSameList.All(x => x));
                            bool isSame = isSameList.All(x => x);

                            //LocalTemplateSingleInfos_Config.CompareTemplate_Disorder_AllInfo(LocalTemplateSingleInfos_Config.temInfos, LocalTemplateSingleInfos_Config.mainInfos);

                            if (LocalInfo.NGControlType == "1")
                            {
                                if (LocalInfo.ngOrOkSignal == "0")
                                {
                                    for (int i = 0; i < isSameList.Count; i++)
                                    {
                                        if (!isSameList[i])
                                        {
                                            IOThread_Run.DO_Trigger_olng((ushort)(i + 1), 1);
                                            Console.WriteLine("ng-------------DO-" + (i + 1).ToString());
                                        }
                                    }
                                    SendIO_NGThread_All.iSendIO_NG_Step = 5;
                                }
                                else if (LocalInfo.ngOrOkSignal == "1")
                                {
                                    for (int i = 0; i < isSameList.Count; i++)
                                    {
                                        if (isSameList[i])
                                        {
                                            IOThread_Run.DO_Trigger_olng((ushort)(i + 1), 1);
                                            Console.WriteLine("ok-------------DO-" + (i + 1).ToString());
                                        }
                                    }

                                    SendIO_NGThread_All.iSendIO_NG_Step = 5;
                                }
                            }

                            dt_CompareResult = DateTime.Now;
                            //Console.WriteLine(isSame);
                            if (!isSame)
                            {
                                Console.WriteLine("GPU-NG");
                                #region  整体判断Ng
                                //if (LocalTemplateSingleInfos_Config.localTemplateSingleInfos.Count >= 1)
                                //{
                                //    IOThread_Run.DO_Trigger_olng(1, 1);
                                //    //SendDt = DateTime.Now;
                                //    SendIO_NGThread.iSendIO_NG_Step = 5;
                                //}
                                //if (LocalTemplateSingleInfos_Config.localTemplateSingleInfos.Count >= 2)
                                //{
                                //    IOThread_Run.DO_Trigger_olng(2, 1);
                                //    //SendDt = DateTime.Now;
                                //    SendIO_NGThread02.iSendIO_NG_Step = 5;
                                //}
                                //if (LocalTemplateSingleInfos_Config.localTemplateSingleInfos.Count >= 3)
                                //{
                                //    IOThread_Run.DO_Trigger_olng(3, 1);
                                //    //SendDt = DateTime.Now;
                                //    SendIO_NGThread03.iSendIO_NG_Step = 5;
                                //}
                                //if (LocalTemplateSingleInfos_Config.localTemplateSingleInfos.Count >= 4)
                                //{
                                //    IOThread_Run.DO_Trigger_olng(4, 1);
                                //    //SendDt = DateTime.Now;
                                //    SendIO_NGThread04.iSendIO_NG_Step = 5;
                                //}
                                #endregion
                                SendDt = DateTime.Now;

                                Console.WriteLine("isSameList:" + isSameList.ToArray().Count(b => b == false));
                                
                                Console.WriteLine("isSameList:"+ Array.FindAll(isSameList.ToArray(), b => !b).Length);

                                int tempNG_Count = isSameList.ToArray().Count(b => b == false);
                                LocalInfo.ngCount += tempNG_Count;

                                //SetFinalInfoThread.iSetFinalInfo_Step = 5;

                                FinalInfoData finalInfoData = new FinalInfoData();
                                finalInfoData.Bitmap = finalBit;
                                //finalInfoData.Bitmap = (Bitmap)finalBit.Clone();
                                finalInfoData.result = "NG";
                                finalInfoData.wrongIndex = LocalInfo.wrongIndex;
                                finalInfoData.wrongString = LocalInfo.wrongString;
                                finalInfoData.isSame = isSameList;
                                OCR_Form.infoQueue.Enqueue(finalInfoData);

                                if (LocalInfo.NGControlType == "0")
                                {
                                    NGControlThread.infoQueue.Enqueue(finalInfoData);
                                    Console.WriteLine("检测队列添加NG后:------------------------" + NGControlThread.infoQueue.Count);
                                }
                                    



                            }
                            else
                            {
                                Console.WriteLine("GPU-OK");
                                SendDt = DateTime.Now;

                                //SetFinalInfoThread.iSetFinalInfo_Step = 10;

                                FinalInfoData finalInfoData = new FinalInfoData();
                                finalInfoData.Bitmap = finalBit;
                                //finalInfoData.Bitmap = (Bitmap)finalBit.Clone();
                                finalInfoData.result = "OK";
                                finalInfoData.wrongIndex = LocalInfo.wrongIndex;
                                finalInfoData.wrongString = LocalInfo.wrongString;
                                finalInfoData.isSame = isSameList;
                                OCR_Form.infoQueue.Enqueue(finalInfoData);

                                if (LocalInfo.NGControlType == "0")
                                {
                                    NGControlThread.infoQueue.Enqueue(finalInfoData);
                                    Console.WriteLine("检测队列添加OK后:------------------------" + NGControlThread.infoQueue.Count);
                                }
                            }

                            if (LocalInfo.CheckDI == "0")
                            {
                                CameraReceiveThread.isImageData = false;
                                CameraReceiveThread.frameForSave = null;
                                iCameraTrigger_Step = 22;
                            }
                            else if (LocalInfo.CheckDI == "1")
                            {
                                CameraReceiveThread.isImageData = false;
                                CameraReceiveThread.frameForSave = null;
                                iCameraTrigger_Step = 10;
                            }
                            //iCameraTrigger_Step = 10;

                        }
                        break;
                    case 25:  //直接判断NG
                        {
                            Console.WriteLine(noImgNG);
                            dt1 = DateTime.Now;

                            LocalInfo.totalCount += 1;
                            dt2 = DateTime.Now;


                            //CameraReceiveThread.isImageData = false;
                            //CameraReceiveThread.frameForSave = null;
                            dt2_Clone = DateTime.Now;

                            dt_CompareResult = DateTime.Now;
                            Console.WriteLine("GPU-NG-noImgNG");

                            if (LocalTemplateSingleInfos_Config.localTemplateSingleInfos.Count >= 1)
                            {
                                IOThread_Run.DO_Trigger_olng(1, 1);
                                SendDt = DateTime.Now;
                            }
                            if (LocalTemplateSingleInfos_Config.localTemplateSingleInfos.Count >= 2)
                            {
                                IOThread_Run.DO_Trigger_olng(2, 1);
                                //SendDt = DateTime.Now;
                            }
                            if (LocalTemplateSingleInfos_Config.localTemplateSingleInfos.Count >= 3)
                            {
                                IOThread_Run.DO_Trigger_olng(3, 1);
                                //SendDt = DateTime.Now;
                            }
                            if (LocalTemplateSingleInfos_Config.localTemplateSingleInfos.Count >= 4)
                            {
                                IOThread_Run.DO_Trigger_olng(4, 1);
                                //SendDt = DateTime.Now;

                            }
                            SendIO_NGThread_All.iSendIO_NG_Step = 5;

                            LocalInfo.ngCount += 1;

                            //SetFinalInfoThread.iSetFinalInfo_Step = 5;

                            //FinalInfoData finalInfoData = new FinalInfoData();
                            //finalInfoData.Bitmap = finalBit;
                            ////finalInfoData.Bitmap = (Bitmap)finalBit.Clone();
                            //finalInfoData.result = "NG";
                            //OCR_Form.infoQueue.Enqueue(finalInfoData);



                            iCameraTrigger_Step = 10;
                            break;
                        }
                    case 30:  //
                        {

                            break;
                        }
                    case 35:
                        {
                            
                            break;
                        }
                    default:
                        {
                            break;
                        }
                }
                Thread.Sleep(1);
            }
        }
    }
}
